﻿using System;
using System.Collections.Generic;

using System.Text;
//引入命名空间
using MongoDB.Driver;
using MongoDB.Bson;
using MongoDB.Driver.Builders;
using System.Collections;
using System.Data;
using MongoDB.Driver.GridFS;

namespace MSL.DataBase.Core
{
    /// <summary>
    /// mongodb的封装类。
    /// add by yancong2008@gmail.com 2011.05.14
    /// </summary>
    public class MongoHelper
    {
        /// <summary>数据库默认链接</summary>
        public static string connectionString_Default = MSL.DataBase.Lib.Config.GetApp("MongoString");// System.Configuration.ConfigurationManager.AppSettings["MongoString"];
        /// <summary>默认数据库</summary>
        public static string database_Default = MSL.DataBase.Lib.Config.GetApp("MongoDataBase");
        /// <summary></summary>
        public static MongoServer _server;
        /// <summary></summary>
        public static MongoDatabase _database;

        #region 操作模式

        /// <summary>
        /// 操作模式
        /// </summary>
        public enum Oprcode
        {
            /// <summary>
            /// 新建
            /// </summary>
            Create,
            /// <summary>
            /// 删除
            /// </summary>
            Drop,
            /// <summary>
            /// 压缩
            /// </summary>
            Repair,
            /// <summary>
            /// 重命名
            /// </summary>
            Rename
        }
        #endregion

        #region 是否为系统数据集

        /// <summary>
        /// 是否为系统数据集[无法删除]
        /// </summary>
        /// <param name="mongoCol"></param>
        /// <returns></returns>
        public static Boolean IsSystemCollection(MongoCollection mongoCol)
        {
            //系统
            if (mongoCol.Name.StartsWith("system.")) { return true; }
            //文件
            if (mongoCol.Name.StartsWith("fs.")) { return true; }
            //local数据库,默认为系统
            if (mongoCol.Database.Name == "local") { return true; }
            //config数据库,默认为系统
            if (mongoCol.Database.Name == "config") { return true; }
            return false;
        }
        /// <summary>
        /// 是否为系统数据库[无法删除]
        /// </summary>
        /// <param name="mongoDB"></param>
        /// <returns></returns>
        public static Boolean IsSystemDataBase(MongoDatabase mongoDB)
        {
            //local数据库,默认为系统
            if (mongoDB.Name == "local") { return true; }
            //config数据库,默认为系统
            if (mongoDB.Name == "config") { return true; }
            return false;
        }
        #endregion

        #region ##
        ///// <summary>
        ///// 数据库操作
        ///// </summary>
        ///// <param name="strSvrPath"></param>
        ///// <param name="DBName"></param>
        ///// <returns></returns>
        //public static Boolean DataBaseOpration(String strSvrPath, String DBName, Oprcode Func, TreeNode tr)
        //{
        //    Boolean rtnResult = false;
        //    MongoServer Mongosrv = GetMongoServerBySvrPath(strSvrPath);
        //    if (Mongosrv != null)
        //    {
        //        switch (Func)
        //        {
        //            case Oprcode.Create:
        //                if (!Mongosrv.DatabaseExists(DBName))
        //                {
        //                    Mongosrv.GetDatabase(DBName);
        //                    tr.Nodes.Add(FillDataBaseInfoToTreeNode(DBName, Mongosrv, strSvrPath.Split("/".ToCharArray())[0]));
        //                    rtnResult = true;
        //                }
        //                break;
        //            case Oprcode.Drop:
        //                if (Mongosrv.DatabaseExists(DBName))
        //                {
        //                    Mongosrv.DropDatabase(DBName);
        //                    tr.TreeView.Nodes.Remove(tr);
        //                    rtnResult = true;
        //                }
        //                break;
        //            case Oprcode.Repair:
        //                //How To Compress?Run Command？？    
        //                break;
        //            default:
        //                break;
        //        }
        //    }
        //    return rtnResult;
        //}
        ///// <summary>
        ///// 数据集操作
        ///// </summary>
        ///// <param name="strSvrPath"></param>
        ///// <param name="CollectionName"></param>
        ///// <param name="Func"></param>
        ///// <returns></returns>
        //public static Boolean CollectionOpration(String strSvrPath, String CollectionName, Oprcode Func, TreeNode mTreenode, String NewCollectionName = "")
        //{
        //    Boolean rtnResult = false;
        //    MongoDatabase Mongodb = GetMongoDBBySvrPath(strSvrPath);
        //    if (Mongodb != null)
        //    {
        //        switch (Func)
        //        {
        //            case Oprcode.Create:
        //                if (!Mongodb.CollectionExists(CollectionName))
        //                {
        //                    Mongodb.CreateCollection(CollectionName);
        //                    mTreenode.Nodes.Add(FillCollectionInfoToTreeNode(CollectionName, Mongodb, strSvrPath.Split("/".ToCharArray())[0]));
        //                    rtnResult = true;
        //                }
        //                break;
        //            case Oprcode.Drop:
        //                if (Mongodb.CollectionExists(CollectionName))
        //                {
        //                    Mongodb.DropCollection(CollectionName);
        //                    mTreenode.TreeView.Nodes.Remove(mTreenode);
        //                    rtnResult = true;
        //                }
        //                break;
        //            case Oprcode.Rename:
        //                if (!Mongodb.CollectionExists(NewCollectionName))
        //                {
        //                    Mongodb.RenameCollection(CollectionName, NewCollectionName);
        //                    mTreenode.Text = NewCollectionName;
        //                    //添加新节点
        //                    mTreenode.Parent.Nodes.Add(FillCollectionInfoToTreeNode(NewCollectionName, Mongodb, strSvrPath.Split("/".ToCharArray())[0]));
        //                    //删除旧节点
        //                    mTreenode.TreeView.Nodes.Remove(mTreenode);
        //                    rtnResult = true;
        //                }
        //                break;
        //            default:
        //                break;
        //        }
        //    }
        //    return rtnResult;
        //}
        ///// <summary>
        ///// 根据路径字符获得服务器
        ///// </summary>
        ///// <param name="strSvrPath">[Service/DBName/Collection]</param>
        ///// <param name="WithTag">是否带有标签</param>
        ///// <returns></returns>
        //public static MongoServer GetMongoServerBySvrPath(String strSvrPath, Boolean WithTag = false)
        //{
        //    if (WithTag)
        //    {
        //        strSvrPath = strSvrPath.Split(":".ToCharArray())[1];
        //    }
        //    MongoServer rtnMongoSrv = null;
        //    String[] strPath = strSvrPath.Split("/".ToCharArray());
        //    if (strPath.Length > 0)
        //    {
        //        if (mongosrvlst.ContainsKey(strPath[(int)PathLv.ServerLV]))
        //        {
        //            rtnMongoSrv = mongosrvlst[strPath[(int)PathLv.ServerLV]];
        //        }
        //    }
        //    return rtnMongoSrv;
        //}
        ///// <summary>
        ///// 根据路径字符获得数据库
        ///// </summary>
        ///// <param name="strSvrPath">[Service/DBName/Collection]</param>
        ///// <param name="WithTag">是否带有标签</param>
        ///// <returns></returns>
        //public static MongoDatabase GetMongoDBBySvrPath(String strSvrPath, Boolean WithTag = false)
        //{
        //    if (WithTag)
        //    {
        //        strSvrPath = strSvrPath.Split(":".ToCharArray())[1];
        //    }
        //    MongoDatabase rtnMongoDb = null;
        //    MongoServer MongoSrv = GetMongoServerBySvrPath(strSvrPath);
        //    if (MongoSrv != null)
        //    {
        //        String[] strPath = strSvrPath.Split("/".ToCharArray());
        //        if (strPath.Length > 1)
        //        {
        //            if (MongoSrv.DatabaseExists(strPath[(int)PathLv.DatabaseLv]))
        //            {
        //                rtnMongoDb = MongoSrv.GetDatabase(strPath[(int)PathLv.DatabaseLv]);
        //            }
        //        }
        //    }
        //    return rtnMongoDb;
        //}
        ///// <summary>
        ///// 通过路径获得数据集
        ///// </summary>
        ///// <param name="strSvrPath"></param>
        ///// <param name="WithTag"></param>
        ///// <returns></returns>
        //public static MongoCollection GetMongoCollectionBySvrPath(String strSvrPath, Boolean WithTag = false)
        //{
        //    //if (WithTag)
        //    //{
        //    //    strSvrPath = strSvrPath.Split(":".ToCharArray())[1];
        //    //}
        //    //MongoCollection rtnMongoCollection = null;
        //    //MongoServer MongoSrv = GetMongoServerBySvrPath(strSvrPath);
        //    //if (MongoSrv != null)
        //    //{
        //    //    String[] strPath = strSvrPath.Split("/".ToCharArray());
        //    //    if (strPath.Length > 1)
        //    //    {
        //    //        if (MongoSrv.DatabaseExists(strPath[(int)PathLv.DatabaseLv]))
        //    //        {
        //    //            rtnMongoCollection = MongoSrv.GetDatabase(strPath[(int)PathLv.DatabaseLv]).GetCollection(strPath[(int)PathLv.CollectionLV]);
        //    //        }
        //    //    }
        //    //}
        //    return rtnMongoCollection;

        //}
        ///// <summary>
        ///// 添加索引
        ///// </summary>
        ///// <param name="KeyName">索引名称</param>
        ///// <param name="IsAccending">是否为升序</param>
        ///// <returns></returns>
        //public static Boolean CreateMongoIndex(String KeyName, Boolean IsAccending = true)
        //{
        //    MongoCollection mongoCol = SystemManager.getCurrentCollection();
        //    IndexKeysDocument index = new IndexKeysDocument();
        //    if (!mongoCol.IndexExists(KeyName))
        //    {
        //        index.Add(KeyName, IsAccending ? 1 : 0);
        //        mongoCol.CreateIndex(index);
        //        return true;
        //    }
        //    return false;
        //}
        ///// <summary>
        ///// 删除索引
        ///// </summary>
        ///// <param name="indexName"></param>
        ///// <returns></returns>
        //public static Boolean DropMongoIndex(String indexName)
        //{
        //    MongoCollection mongoCol = SystemManager.getCurrentCollection();
        //    if (mongoCol.IndexExistsByName(indexName))
        //    {
        //        mongoCol.DropIndexByName(indexName);
        //    }
        //    return true;
        //}
        ///// <summary>
        ///// 插入JS到系统JS库
        ///// </summary>
        ///// <param name="JsName"></param>
        ///// <param name="JsCode"></param>
        //public static Boolean SaveJavascript(String JsName, String JsCode)
        //{
        //    //标准的JS库格式未知
        //    //MongoCollection JsCol = SystemManager.getCurrentJsCollection();
        //    //if (!IsExistByField(JsCol, JsName))
        //    //{
        //    //    JsCol.Insert<BsonDocument>(new BsonDocument().Add("_id", JsName).Add("value", JsCode));
        //    //    return true;
        //    //}
        //    return false;
        //}
        ///// <summary>
        ///// 获得JS代码
        ///// </summary>
        ///// <param name="JsName"></param>
        ///// <returns></returns>
        //public static String LoadJavascript(String JsName)
        //{
        //    MongoCollection JsCol = SystemManager.getCurrentJsCollection();
        //    if (IsExistByField(JsCol, JsName))
        //    {
        //        return JsCol.FindOneAs<BsonDocument>(Query.EQ("_id", JsName)).GetValue("value").ToString();
        //    }
        //    return String.Empty;
        //}
        ///// <summary>
        ///// 删除数据
        ///// </summary>
        ///// <param name="MongoCol"></param>
        ///// <param name="strKey"></param>
        ///// <param name="KeyField"></param>
        ///// <returns></returns>
        //public static Boolean DropRecord(MongoCollection MongoCol, Object strKey, String KeyField = "_id")
        //{
        //    if (IsExistByField(MongoCol, (BsonValue)strKey, KeyField))
        //    {
        //        MongoCol.Remove(Query.EQ(KeyField, (BsonValue)strKey));
        //    }
        //    return true;
        //}
        #endregion

        #region 增删上传下载 GridFS
        ///在使用GirdFileSystem的时候，请注意：
        ///1.Windows 系统的文件名不区分大小写，不过，filename一定是区分大小写的，如果大小写不匹配的话，会发生无法找到文件的问题
        ///2.Download的时候，不能使用SlaveOk选项！
        /// <summary>
        /// 打开文件
        /// </summary>
        /// <param name="connectionString">链接</param>
        /// <param name="databaseName">数据库名</param>
        /// <param name="strRemoteFileName">远程文件名</param>
        public static void OpenFile(string connectionString, string databaseName, String strRemoteFileName)
        {
            GetServer(connectionString);
            GetDatabase(databaseName);
            MongoGridFS gfs = _database.GetGridFS(new MongoGridFSSettings());

            String[] strLocalFileName = strRemoteFileName.Split(@"\".ToCharArray());
            try
            {
                gfs.Download(strLocalFileName[strLocalFileName.Length - 1], strRemoteFileName);
                System.Diagnostics.Process.Start(strLocalFileName[strLocalFileName.Length - 1]);
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="strFileName"></param>
        public static void DownloadFile(string connectionString, string databaseName, String strLocalFileName, String strRemoteFileName)
        {
            GetServer(connectionString);
            GetDatabase(databaseName);
            MongoGridFS gfs = _database.GetGridFS(new MongoGridFSSettings());
            gfs.Download(strLocalFileName, strRemoteFileName);
        }
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="strFileName"></param>
        public static void UpLoadFile(string connectionString, string databaseName, String strFileName)
        {
            GetServer(connectionString);
            GetDatabase(databaseName);
            MongoGridFS gfs = _database.GetGridFS(new MongoGridFSSettings());
            gfs.Upload(strFileName);
        }
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="strFileName"></param>
        public static void DeleteFile(string connectionString, string databaseName, String strFileName)
        {
            GetServer(connectionString);
            GetDatabase(databaseName);
            MongoGridFS gfs = _database.GetGridFS(new MongoGridFSSettings());
            gfs.Delete(strFileName);
        }
        #endregion

        #region 创建服务

        /// <summary>
        /// 创建数据库服务
        /// </summary>
        /// <param name="connectionString">数据库链接</param>
        /// <returns></returns>
        public static void GetServer(string connectionString)
        {
            _server = MongoServer.Create(connectionString);
        }
        /// <summary>
        /// 创建数据库服务
        /// </summary>
        /// <returns></returns>
        public static void GetServer()
        {
            GetServer(connectionString_Default);
        }
        #endregion

        #region 获取数据库

        /// <summary>
        /// 获取数据库或者创建数据库
        /// </summary>
        /// <param name="databaseName">数据库名</param>
        /// <returns></returns>
        public static void GetDatabase(string databaseName)
        {
            _database = _server.GetDatabase(databaseName);
        }
        /// <summary>
        /// 获取数据库或者创建数据库
        /// </summary>
        /// <returns></returns>
        public static void GetDatabase()
        {
            _database = _server.GetDatabase(database_Default);
        }
        #endregion

        #region 数据库连接字符串
        /// <summary>
        /// 
        /// </summary>
        /// <param name="MongoDBConn"></param>
        /// <param name="MongoDBName"></param>
        public static void ResetDbProvider(string MongoDBConn, string MongoDBName)
        {
            connectionString_Default = MongoDBConn;
            database_Default = MongoDBName;
        }

        #endregion

        #region 添加
        public static WriteConcernResult InsertOne<T>(string collectionName, T entity)
        {
            return MongoHelper.InsertOne<T>(MongoHelper.connectionString_Default, MongoHelper.database_Default, collectionName, entity);
        }
        public static WriteConcernResult InsertOne<T>(string connectionString, string databaseName, string collectionName, T entity)
        {
            WriteConcernResult result = null;// new SafeModeResult();
            if (null == entity)
            {
                return null;
            }
            GetServer(connectionString);
            GetDatabase(databaseName);
            using (_server.RequestStart(_database))//开始连接数据库。
            {
                MongoCollection<BsonDocument> myCollection = _database.GetCollection<BsonDocument>(collectionName);
                result = myCollection.Insert(entity);

            }
            return result;
        }
        public static IEnumerable<SafeModeResult> InsertAll<T>(string collectionName, IEnumerable<T> entitys)
        {
            return MongoHelper.InsertAll<T>(MongoHelper.connectionString_Default, MongoHelper.database_Default, collectionName, entitys);
        }
        public static IEnumerable<SafeModeResult> InsertAll<T>(string connectionString, string databaseName, string collectionName, IEnumerable<T> entitys)
        {
            IEnumerable<SafeModeResult> result = null;
            if (null == entitys)
            {
                return null;
            }
            GetServer(connectionString);
            GetDatabase(databaseName);
            using (_server.RequestStart(_database))//开始连接数据库。
            {
                MongoCollection<BsonDocument> myCollection = _database.GetCollection<BsonDocument>(collectionName);
                result = myCollection.InsertBatch(entitys);
            }
            return result;
        }

        #endregion

        #region 添加（参数化）

        /// <summary>
        /// DataRow添加到MongoDB 2013-6-28 马山林 添加
        /// </summary>
        /// <param name="collectionName">集合名</param>
        /// <param name="columns"></param>
        /// <returns></returns>
        public static SafeModeResult InsertOne(string collectionName, Hashtable columns)
        {
            return InsertOne(connectionString_Default, database_Default, collectionName, columns);
        }

        /// <summary>
        /// DataRow添加到MongoDB 2013-6-28 马山林 添加
        /// </summary>
        /// <param name="databaseName">库名</param>
        /// <param name="collectionName">集合名</param>
        /// <param name="columns"></param>
        /// <returns></returns>
        public static SafeModeResult InsertOne(string databaseName, string collectionName, Hashtable columns)
        {
            return InsertOne(connectionString_Default, databaseName, collectionName, columns);
        }

        /// <summary>
        /// DataRow添加到MongoDB 2013-6-28 马山林 添加
        /// </summary>
        /// <param name="connectionString">链接</param>
        /// <param name="databaseName">库名</param>
        /// <param name="collectionName">集合名</param>
        /// <param name="columns"></param>
        /// <returns></returns>
        public static SafeModeResult InsertOne(string connectionString, string databaseName, string collectionName, Hashtable columns)
        {
            if (columns == null)
            {
                return null;
            }
            BsonDocument document = new BsonDocument();
            foreach (DictionaryEntry column in columns)
            {
                if (column.Key == null || column.Key.ToString() == "")
                    continue;

                BsonValue bsonValue;
                var value = column.Value;
                switch (value.GetType().ToString())
                {
                    case "System.Decl":
                        value = Convert.ToDouble(value);
                        break;
                    case "System.DBNull":
                        value = "";
                        break;
                }

                document.Add(column.Key.ToString(), BsonTypeMapper.TryMapToBsonValue(value, out bsonValue) ? bsonValue : value.ToString());
            }
            return MongoHelper.InsertOne<BsonDocument>(connectionString, databaseName, collectionName, document);
        }

        #endregion

        #region DataTable添加到MongoDB
        /// <summary>
        /// DataRow添加到MongoDB 2013-6-18 马山林 添加
        /// </summary>
        /// <param name="connectionString">链接</param>
        /// <param name="databaseName">库名</param>
        /// <param name="collectionName">集合名</param>
        /// <param name="dr">DataRow对象</param>
        /// <param name="columns">DataColumnCollection</param>
        /// <returns></returns>
        public static SafeModeResult InsertOne(string connectionString, string databaseName, string collectionName, DataRow dr, DataColumnCollection columns)
        {
            if (dr == null)
            {
                return null;
            }
            BsonDocument document = new BsonDocument();
            foreach (DataColumn column in columns)
            {
                BsonValue bsonValue;
                var value = dr[column];
                switch (value.GetType().ToString())
                {
                    case "System.Decl":
                        value = Convert.ToDouble(value);
                        break;
                    case "System.DBNull":
                        value = "";
                        break;
                }
                document.Add(column.ColumnName, BsonTypeMapper.TryMapToBsonValue(value, out bsonValue) ? bsonValue : value.ToString());
            }
            return MongoHelper.InsertOne<BsonDocument>(connectionString, databaseName, collectionName, document);
        }
        /// <summary>
        /// DataRow添加到MongoDB
        /// </summary>
        /// <param name="collectionName">集合名</param>
        /// <param name="dr">DataRow对象</param>
        /// <param name="columns">DataColumnCollection</param>
        /// <returns></returns>
        public static SafeModeResult InsertOne(string collectionName, DataRow dr, DataColumnCollection columns)
        {
            return InsertOne(connectionString_Default, database_Default, collectionName, dr, columns);
        }
        /// <summary>
        /// DataTable添加到MongoDB
        /// </summary>
        /// <param name="connectionString">链接</param>
        /// <param name="databaseName">库名</param>
        /// <param name="collectionName">集合名</param>
        /// <param name="dt">DataTable对象</param>
        /// <returns></returns>
        public static int Insert(string connectionString, string databaseName, string collectionName, DataTable dt)
        {
            if (dt == null || dt.Rows.Count == 0)
            {
                return 0;
            }
            DataColumnCollection columns = dt.Columns;
            int succCount = 0;//成功数
            foreach (DataRow dr in dt.Rows)
            {
                try
                {
                    InsertOne(connectionString, databaseName, collectionName, dr, columns);
                    succCount++;
                }
                catch (Exception)
                {

                }
            }
            return succCount;
        }
        /// <summary>
        /// DataTable添加到MongoDB
        /// </summary>
        /// <param name="collectionName">集合名</param>
        /// <param name="dt">DataTable对象</param>
        /// <returns></returns>
        public static int Insert(string collectionName, DataTable dt)
        {
            return Insert(connectionString_Default, database_Default, collectionName, dt);
        }

        #endregion

        #region 修改
        public static SafeModeResult UpdateOne<T>(string collectionName, T entity)
        {
            return MongoHelper.UpdateOne<T>(MongoHelper.connectionString_Default, MongoHelper.database_Default, collectionName, entity);
        }
        public static SafeModeResult UpdateOne<T>(string connectionString, string databaseName, string collectionName, T entity)
        {
            GetServer(connectionString);
            GetDatabase(databaseName);
            SafeModeResult result;
            using (_server.RequestStart(_database))//开始连接数据库。
            {
                MongoCollection<BsonDocument> myCollection = _database.GetCollection<BsonDocument>(collectionName);
                result = myCollection.Save(entity);
            }
            return result;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="collectionName"></param>
        /// <param name="query">条件查询。 调用示例：Query.Matches("Title", "感冒") 或者 Query.EQ("Title", "感冒") 或者Query.And(Query.Matches("Title", "感冒"),Query.EQ("Author", "yanc")) 等等</param>
        /// <param name="update">更新设置。调用示例：Update.Set("Title", "yanc") 或者 Update.Set("Title", "yanc").Set("Author", "yanc2") 等等</param>
        /// <returns></returns>
        public static SafeModeResult UpdateAll<T>(string collectionName, IMongoQuery query, IMongoUpdate update)
        {
            return MongoHelper.UpdateAll<T>(MongoHelper.connectionString_Default, MongoHelper.database_Default, collectionName, query, update);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="connectionString"></param>
        /// <param name="databaseName"></param>
        /// <param name="collectionName"></param>
        /// <param name="query">条件查询。 调用示例：Query.Matches("Title", "感冒") 或者 Query.EQ("Title", "感冒") 或者Query.And(Query.Matches("Title", "感冒"),Query.EQ("Author", "yanc")) 等等</param>
        /// <param name="update">更新设置。调用示例：Update.Set("Title", "yanc") 或者 Update.Set("Title", "yanc").Set("Author", "yanc2") 等等</param>
        /// <returns></returns>
        public static SafeModeResult UpdateAll<T>(string connectionString, string databaseName, string collectionName, IMongoQuery query, IMongoUpdate update)
        {
            SafeModeResult result;
            if (null == query || null == update)
            {
                return null;
            }
            GetServer(connectionString);
            GetDatabase(databaseName);
            using (_server.RequestStart(_database))//开始连接数据库。
            {
                MongoCollection<BsonDocument> myCollection = _database.GetCollection<BsonDocument>(collectionName);
                result = myCollection.Update(query, update, UpdateFlags.Multi);
            }
            return result;
        }
        #endregion

        #region 删除
        public static SafeModeResult Delete(string collectionName, string _id)
        {
            return MongoHelper.Delete(MongoHelper.connectionString_Default, MongoHelper.database_Default, collectionName, _id);
        }
        public static SafeModeResult Delete(string connectionString, string databaseName, string collectionName, string _id)
        {
            SafeModeResult result;
            ObjectId id;
            if (!ObjectId.TryParse(_id, out id))
            {
                return null;
            }
            GetServer(connectionString);
            GetDatabase(databaseName);
            using (_server.RequestStart(_database))//开始连接数据库。
            {
                MongoCollection<BsonDocument> myCollection = _database.GetCollection<BsonDocument>(collectionName);
                result = myCollection.Remove(Query.EQ("_id", id));
            }
            return result;
        }
        public static SafeModeResult DeleteAll(string collectionName)
        {
            return MongoHelper.DeleteAll(MongoHelper.connectionString_Default, MongoHelper.database_Default, collectionName, null);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="collectionName"></param>
        /// <param name="query">条件查询。 调用示例：Query.Matches("Title", "感冒") 或者 Query.EQ("Title", "感冒") 或者Query.And(Query.Matches("Title", "感冒"),Query.EQ("Author", "yanc")) 等等</param>
        /// <returns></returns>
        public static SafeModeResult DeleteAll(string collectionName, IMongoQuery query)
        {
            return MongoHelper.DeleteAll(MongoHelper.connectionString_Default, MongoHelper.database_Default, collectionName, query);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="connectionString"></param>
        /// <param name="databaseName"></param>
        /// <param name="collectionName"></param>
        /// <param name="query">条件查询。 调用示例：Query.Matches("Title", "感冒") 或者 Query.EQ("Title", "感冒") 或者Query.And(Query.Matches("Title", "感冒"),Query.EQ("Author", "yanc")) 等等</param>
        /// <returns></returns>
        public static SafeModeResult DeleteAll(string connectionString, string databaseName, string collectionName, IMongoQuery query)
        {
            GetServer(connectionString);
            GetDatabase(databaseName);
            SafeModeResult result;
            using (_server.RequestStart(_database))//开始连接数据库。
            {
                MongoCollection<BsonDocument> myCollection = _database.GetCollection<BsonDocument>(collectionName);
                if (null == query)
                {
                    result = myCollection.RemoveAll();
                }
                else
                {
                    result = myCollection.Remove(query);
                }
            }
            return result;
        }
        #endregion

        #region 获取单条信息
        public static T GetOne<T>(string collectionName, string _id)
        {
            return MongoHelper.GetOne<T>(MongoHelper.connectionString_Default, MongoHelper.database_Default, collectionName, _id);
        }
        public static T GetOne<T>(string connectionString, string databaseName, string collectionName, string _id)
        {
            T result = default(T);
            ObjectId id;
            if (!ObjectId.TryParse(_id, out id))
            {
                return default(T);
            }
            GetServer(connectionString);
            GetDatabase(databaseName);
            using (_server.RequestStart(_database))//开始连接数据库。
            {
                MongoCollection<BsonDocument> myCollection = _database.GetCollection<BsonDocument>(collectionName);
                result = myCollection.FindOneAs<T>(Query.EQ("_id", id));
            }
            return result;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="collectionName"></param>
        /// <param name="query">条件查询。 调用示例：Query.Matches("Title", "感冒") 或者 Query.EQ("Title", "感冒") 或者Query.And(Query.Matches("Title", "感冒"),Query.EQ("Author", "yanc")) 等等</param>
        /// <returns></returns>
        public static T GetOne<T>(string collectionName, IMongoQuery query)
        {
            return GetOne<T>(MongoHelper.connectionString_Default, MongoHelper.database_Default, collectionName, query);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="connectionString"></param>
        /// <param name="databaseName"></param>
        /// <param name="collectionName"></param>
        /// <param name="query">条件查询。 调用示例：Query.Matches("Title", "感冒") 或者 Query.EQ("Title", "感冒") 或者Query.And(Query.Matches("Title", "感冒"),Query.EQ("Author", "yanc")) 等等</param>
        /// <returns></returns>
        public static T GetOne<T>(string connectionString, string databaseName, string collectionName, IMongoQuery query)
        {
            GetServer(connectionString);
            GetDatabase(databaseName);
            T result = default(T);
            using (_server.RequestStart(_database))//开始连接数据库。
            {
                MongoCollection<BsonDocument> myCollection = _database.GetCollection<BsonDocument>(collectionName);
                if (null == query)
                {
                    result = myCollection.FindOneAs<T>();
                }
                else
                {
                    result = myCollection.FindOneAs<T>(query);
                }
            }
            return result;
        }

        #endregion

        #region 获取多个
        public static List<T> GetAll<T>(string collectionName)
        {
            return MongoHelper.GetAll<T>(MongoHelper.connectionString_Default, MongoHelper.database_Default, collectionName);
        }
        /// <summary>
        /// 如果不清楚具体的数量，一般不要用这个函数。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="collectionName"></param>
        /// <returns></returns>
        public static List<T> GetAll<T>(string connectionString, string databaseName, string collectionName)
        {
            GetServer(connectionString);
            GetDatabase(databaseName);
            List<T> result = new List<T>();
            using (_server.RequestStart(_database))//开始连接数据库。
            {
                MongoCollection<BsonDocument> myCollection = _database.GetCollection<BsonDocument>(collectionName);
                foreach (T entity in myCollection.FindAllAs<T>())
                {
                    result.Add(entity);
                }
            }
            return result;
        }
        public static List<T> GetAll<T>(string collectionName, int count)
        {
            return MongoHelper.GetAll<T>(collectionName, count, null, null);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="collectionName"></param>
        /// <param name="count"></param>
        /// <param name="query">条件查询。 调用示例：Query.Matches("Title", "感冒") 或者 Query.EQ("Title", "感冒") 或者Query.And(Query.Matches("Title", "感冒"),Query.EQ("Author", "yanc")) 等等</param>
        /// <returns></returns>
        public static List<T> GetAll<T>(string collectionName, int count, IMongoQuery query)
        {
            return MongoHelper.GetAll<T>(collectionName, count, query, null);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="collectionName"></param>
        /// <param name="count"></param>
        /// <param name="sortBy">排序用的。调用示例：SortBy.Descending("Title") 或者 SortBy.Descending("Title").Ascending("Author")等等</param>
        /// <returns></returns>
        public static List<T> GetAll<T>(string collectionName, int count, IMongoSortBy sortBy)
        {
            return MongoHelper.GetAll<T>(collectionName, count, null, sortBy);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="collectionName"></param>
        /// <param name="count"></param>
        /// <param name="query">条件查询。 调用示例：Query.Matches("Title", "感冒") 或者 Query.EQ("Title", "感冒") 或者Query.And(Query.Matches("Title", "感冒"),Query.EQ("Author", "yanc")) 等等</param>
        /// <param name="sortBy">排序用的。调用示例：SortBy.Descending("Title") 或者 SortBy.Descending("Title").Ascending("Author")等等</param>
        /// <param name="fields">只返回所需要的字段的数据。调用示例："Title" 或者 new string[] { "Title", "Author" }等等</param>
        /// <returns></returns>
        public static List<T> GetAll<T>(string collectionName, int count, IMongoQuery query, IMongoSortBy sortBy, params string[] fields)
        {
            PagerInfo pagerInfo = new PagerInfo();
            pagerInfo.Page = 1;
            pagerInfo.PageSize = count;
            return MongoHelper.GetAll<T>(MongoHelper.connectionString_Default, MongoHelper.database_Default, collectionName, query, pagerInfo, sortBy, fields);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="collectionName"></param>
        /// <param name="query">条件查询。 调用示例：Query.Matches("Title", "感冒") 或者 Query.EQ("Title", "感冒") 或者Query.And(Query.Matches("Title", "感冒"),Query.EQ("Author", "yanc")) 等等</param>
        /// <param name="pagerInfo"></param>
        /// <returns></returns>
        public static List<T> GetAll<T>(string collectionName, IMongoQuery query, PagerInfo pagerInfo)
        {
            return MongoHelper.GetAll<T>(MongoHelper.connectionString_Default, MongoHelper.database_Default, collectionName, query, pagerInfo, null);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="collectionName"></param>
        /// <param name="query">条件查询。 调用示例：Query.Matches("Title", "感冒") 或者 Query.EQ("Title", "感冒") 或者Query.And(Query.Matches("Title", "感冒"),Query.EQ("Author", "yanc")) 等等</param>
        /// <param name="pagerInfo"></param>
        /// <param name="sortBy">排序用的。调用示例：SortBy.Descending("Title") 或者 SortBy.Descending("Title").Ascending("Author")等等</param>
        /// <returns></returns>
        public static List<T> GetAll<T>(string collectionName, IMongoQuery query, PagerInfo pagerInfo, IMongoSortBy sortBy)
        {
            return MongoHelper.GetAll<T>(MongoHelper.connectionString_Default, MongoHelper.database_Default, collectionName, query, pagerInfo, sortBy);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="collectionName"></param>
        /// <param name="query">条件查询。 调用示例：Query.Matches("Title", "感冒") 或者 Query.EQ("Title", "感冒") 或者Query.And(Query.Matches("Title", "感冒"),Query.EQ("Author", "yanc")) 等等</param>
        /// <param name="pagerInfo"></param>
        /// <param name="fields">只返回所需要的字段的数据。调用示例："Title" 或者 new string[] { "Title", "Author" }等等</param>
        /// <returns></returns>
        public static List<T> GetAll<T>(string collectionName, IMongoQuery query, PagerInfo pagerInfo, params string[] fields)
        {
            return MongoHelper.GetAll<T>(MongoHelper.connectionString_Default, MongoHelper.database_Default, collectionName, query, pagerInfo, null, fields);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="collectionName"></param>
        /// <param name="query">条件查询。 调用示例：Query.Matches("Title", "感冒") 或者 Query.EQ("Title", "感冒") 或者Query.And(Query.Matches("Title", "感冒"),Query.EQ("Author", "yanc")) 等等</param>
        /// <param name="pagerInfo"></param>
        /// <param name="sortBy">排序用的。调用示例：SortBy.Descending("Title") 或者 SortBy.Descending("Title").Ascending("Author")等等</param>
        /// <param name="fields">只返回所需要的字段的数据。调用示例："Title" 或者 new string[] { "Title", "Author" }等等</param>
        /// <returns></returns>
        public static List<T> GetAll<T>(string collectionName, IMongoQuery query, PagerInfo pagerInfo, IMongoSortBy sortBy, params string[] fields)
        {
            return MongoHelper.GetAll<T>(MongoHelper.connectionString_Default, MongoHelper.database_Default, collectionName, query, pagerInfo, sortBy, fields);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="collectionName"></param>
        /// <param name="recordCount">总记录数</param>
        /// <param name="query">条件查询。 调用示例：Query.Matches("Title", "感冒") 或者 Query.EQ("Title", "感冒") 或者Query.And(Query.Matches("Title", "感冒"),Query.EQ("Author", "yanc")) 等等</param>
        /// <param name="pagerInfo"></param>
        /// <param name="sortBy">排序用的。调用示例：SortBy.Descending("Title") 或者 SortBy.Descending("Title").Ascending("Author")等等</param>
        /// <param name="fields">只返回所需要的字段的数据。调用示例："Title" 或者 new string[] { "Title", "Author" }等等</param>
        /// <returns></returns>
        public static List<T> GetAll<T>(string collectionName, IMongoQuery query, PagerInfo pagerInfo, IMongoSortBy sortBy, out long recordCount, params string[] fields)
        {
            return MongoHelper.GetAll<T>(MongoHelper.connectionString_Default, MongoHelper.database_Default, collectionName, query, pagerInfo, sortBy, out recordCount, fields);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="connectionString"></param>
        /// <param name="databaseName"></param>
        /// <param name="recordCount">总记录数</param>
        /// <param name="collectionName"></param>
        /// <param name="query">条件查询。 调用示例：Query.Matches("Title", "感冒") 或者 Query.EQ("Title", "感冒") 或者Query.And(Query.Matches("Title", "感冒"),Query.EQ("Author", "yanc")) 等等</param>
        /// <param name="pagerInfo"></param>
        /// <param name="sortBy">排序用的。调用示例：SortBy.Descending("Title") 或者 SortBy.Descending("Title").Ascending("Author")等等</param>
        /// <param name="fields">只返回所需要的字段的数据。调用示例："Title" 或者 new string[] { "Title", "Author" }等等</param>
        /// <returns></returns>
        public static List<T> GetAll<T>(string connectionString, string databaseName, string collectionName, IMongoQuery query, PagerInfo pagerInfo, IMongoSortBy sortBy, out long recordCount, params string[] fields)
        {
            GetServer(connectionString);
            GetDatabase(databaseName);
            List<T> result = new List<T>();
            recordCount = 0;
            using (_server.RequestStart(_database))//开始连接数据库。
            {
                MongoCollection<BsonDocument> myCollection = _database.GetCollection<BsonDocument>(collectionName);
                MongoCursor<T> myCursor;
                if (null == query)
                {
                    myCursor = myCollection.FindAllAs<T>();
                    recordCount = myCollection.Count();
                }
                else
                {
                    myCursor = myCollection.FindAs<T>(query);
                    recordCount = myCollection.Count(query);
                }
                if (null != sortBy)
                {
                    myCursor.SetSortOrder(sortBy);
                }
                if (null != fields)
                {
                    myCursor.SetFields(fields);
                }
                foreach (T entity in myCursor.SetSkip((pagerInfo.Page - 1) * pagerInfo.PageSize).SetLimit(pagerInfo.PageSize))//.SetSkip(100).SetLimit(10)是指读取第一百条后的10条数据。
                {
                    result.Add(entity);
                }
            }

            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="connectionString"></param>
        /// <param name="databaseName"></param>
        /// <param name="collectionName"></param>
        /// <param name="query">条件查询。 调用示例：Query.Matches("Title", "感冒") 或者 Query.EQ("Title", "感冒") 或者Query.And(Query.Matches("Title", "感冒"),Query.EQ("Author", "yanc")) 等等</param>
        /// <param name="pagerInfo"></param>
        /// <param name="sortBy">排序用的。调用示例：SortBy.Descending("Title") 或者 SortBy.Descending("Title").Ascending("Author")等等</param>
        /// <param name="fields">只返回所需要的字段的数据。调用示例："Title" 或者 new string[] { "Title", "Author" }等等</param>
        /// <returns></returns>
        public static List<T> GetAll<T>(string connectionString, string databaseName, string collectionName, IMongoQuery query, PagerInfo pagerInfo, IMongoSortBy sortBy, params string[] fields)
        {
            GetServer(connectionString);
            GetDatabase(databaseName);
            List<T> result = new List<T>();
            using (_server.RequestStart(_database))//开始连接数据库。
            {
                MongoCollection<BsonDocument> myCollection = _database.GetCollection<BsonDocument>(collectionName);
                MongoCursor<T> myCursor;
                if (null == query)
                {
                    myCursor = myCollection.FindAllAs<T>();
                }
                else
                {
                    myCursor = myCollection.FindAs<T>(query);
                }
                if (null != sortBy)
                {
                    myCursor.SetSortOrder(sortBy);
                }
                if (null != fields)
                {
                    myCursor.SetFields(fields);
                }
                foreach (T entity in myCursor.SetSkip((pagerInfo.Page - 1) * pagerInfo.PageSize).SetLimit(pagerInfo.PageSize))//.SetSkip(100).SetLimit(10)是指读取第一百条后的10条数据。
                {
                    result.Add(entity);
                }
            }
            return result;
        }

        #endregion

        #region 分组

        /// <summary>
        /// 分组  2013-01-11 马山林 添加
        /// </summary>
        /// <param name="connectionString"></param>
        /// <param name="databaseName"></param>
        /// <param name="collectionName"></param>
        /// <param name="query"></param>条件查询。 调用示例：Query.Matches("Title", "感冒") 或者 Query.EQ("Title", "感冒") 或者Query.And(Query.Matches("Title", "感冒"),Query.EQ("Author", "yanc")) 等等
        /// <param name="key">分组键</param>
        /// <param name="initial">初始化</param>
        /// <param name="reduce"></param>
        /// <param name="finalize"></param>
        /// <returns></returns>
        public static IEnumerable<BsonDocument> Group(string connectionString, string databaseName, string collectionName, IMongoQuery query, string key, BsonDocument initial, BsonJavaScript reduce, BsonJavaScript finalize)
        {
            GetServer(connectionString);
            GetDatabase(databaseName);
            IEnumerable<BsonDocument> result = null;
            using (_server.RequestStart(_database))//开始连接数据库。
            {
                MongoCollection<BsonDocument> myCollection = _database.GetCollection<BsonDocument>(collectionName);
                if (null == query)
                {
                    result = myCollection.Group(query, key, initial, reduce, finalize);
                }
            }
            return result;
        }

        /// <summary>
        /// 分组  2013-01-11 马山林 添加
        /// </summary>
        /// <param name="connectionString"></param>
        /// <param name="databaseName"></param>
        /// <param name="collectionName"></param>
        /// <param name="query"></param>条件查询。 调用示例：Query.Matches("Title", "感冒") 或者 Query.EQ("Title", "感冒") 或者Query.And(Query.Matches("Title", "感冒"),Query.EQ("Author", "yanc")) 等等
        /// <param name="keyFunction"></param>
        /// <param name="initial"></param>
        /// <param name="reduce"></param>
        /// <param name="finalize"></param>
        /// <returns></returns>
        public static IEnumerable<BsonDocument> Group(string connectionString, string databaseName, string collectionName, IMongoQuery query, BsonJavaScript keyFunction, BsonDocument initial, BsonJavaScript reduce, BsonJavaScript finalize)
        {
            GetServer(connectionString);
            GetDatabase(databaseName);
            IEnumerable<BsonDocument> result = null;
            using (_server.RequestStart(_database))//开始连接数据库。
            {
                MongoCollection<BsonDocument> myCollection = _database.GetCollection<BsonDocument>(collectionName);
                if (null == query)
                {
                    result = myCollection.Group(query, keyFunction, initial, reduce, finalize);
                }
            }
            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="connectionString"></param>
        /// <param name="databaseName"></param>
        /// <param name="collectionName"></param>
        /// <param name="query"></param>条件查询。 调用示例：Query.Matches("Title", "感冒") 或者 Query.EQ("Title", "感冒") 或者Query.And(Query.Matches("Title", "感冒"),Query.EQ("Author", "yanc")) 等等
        /// <param name="keys"></param>
        /// <param name="initial"></param>
        /// <param name="reduce"></param>
        /// <param name="finalize"></param>
        /// <returns></returns>
        public static IEnumerable<BsonDocument> Group(string connectionString, string databaseName, string collectionName, IMongoQuery query, IMongoGroupBy keys, BsonDocument initial, BsonJavaScript reduce, BsonJavaScript finalize)
        {
            GetServer(connectionString);
            GetDatabase(databaseName);
            IEnumerable<BsonDocument> result = null;
            using (_server.RequestStart(_database))//开始连接数据库。
            {
                MongoCollection<BsonDocument> myCollection = _database.GetCollection<BsonDocument>(collectionName);
                if (null == query)
                {
                    result = myCollection.Group(query, keys, initial, reduce, finalize);
                }
            }
            return result;
        }
        #endregion

        #region Distinct

        /// <summary>
        /// 字段排重 2012-11-29 马山林 添加
        /// </summary>
        /// <param name="connectionString"></param>
        /// <param name="databaseName"></param>
        /// <param name="collectionName"></param>
        /// <param name="key"></param>
        /// <param name="query"></param>条件查询。 调用示例：Query.Matches("Title", "感冒") 或者 Query.EQ("Title", "感冒") 或者Query.And(Query.Matches("Title", "感冒"),Query.EQ("Author", "yanc")) 等等
        /// <returns></returns>
        public static IEnumerable<BsonValue> Distinct(string connectionString, string databaseName, string collectionName, string key, IMongoQuery query)
        {
            GetServer(connectionString);
            GetDatabase(databaseName);
            IEnumerable<BsonValue> result = null;
            using (_server.RequestStart(_database))//开始连接数据库。
            {
                MongoCollection<BsonDocument> myCollection = _database.GetCollection<BsonDocument>(collectionName);
                if (null == query)
                {
                    result = myCollection.Distinct(key);
                }
                else
                {
                    result = myCollection.Distinct(key, query);
                }
            }
            return result;
        }

        /// <summary>
        /// 字段排重 2012-11-29 马山林 添加
        /// </summary>
        /// <param name="collectionName"></param>
        /// <param name="key"></param>
        /// <param name="query"></param>条件查询。 调用示例：Query.Matches("Title", "感冒") 或者 Query.EQ("Title", "感冒") 或者Query.And(Query.Matches("Title", "感冒"),Query.EQ("Author", "yanc")) 等等
        /// <returns></returns>
        public static IEnumerable<BsonValue> Distinct(string collectionName, string key, IMongoQuery query)
        {
            GetServer(MongoHelper.connectionString_Default);
            GetDatabase(MongoHelper.database_Default);
            IEnumerable<BsonValue> result = null;
            using (_server.RequestStart(_database))//开始连接数据库。
            {
                MongoCollection<BsonDocument> myCollection = _database.GetCollection<BsonDocument>(collectionName);
                if (null == query)
                {
                    result = myCollection.Distinct(key);
                }
                else
                {
                    result = myCollection.Distinct(key, query);
                }
            }
            return result;
        }
        #endregion

        #region Count

        /// <summary>
        /// 数量  2012-11-29 马山林 添加
        /// </summary>
        /// <param name="collectionName"></param>
        /// <param name="query"></param>条件查询。 调用示例：Query.Matches("Title", "感冒") 或者 Query.EQ("Title", "感冒") 或者Query.And(Query.Matches("Title", "感冒"),Query.EQ("Author", "yanc")) 等等
        /// <returns></returns>
        public static long Count(string collectionName, IMongoQuery query)
        {
            GetServer(MongoHelper.connectionString_Default);
            GetDatabase(MongoHelper.database_Default);
            long result = 0;
            using (_server.RequestStart(_database))//开始连接数据库。
            {
                MongoCollection<BsonDocument> myCollection = _database.GetCollection<BsonDocument>(collectionName);
                if (null == query)
                {
                    result = myCollection.Count();
                }
                else
                {
                    result = myCollection.Count(query);
                }
            }
            return result;
        }

        /// <summary>
        /// 数量  2012-11-29 马山林 添加 
        /// </summary>
        /// <param name="connectionString"></param>
        /// <param name="databaseName"></param>
        /// <param name="collectionName"></param>
        /// <param name="query"></param>条件查询。 调用示例：Query.Matches("Title", "感冒") 或者 Query.EQ("Title", "感冒") 或者Query.And(Query.Matches("Title", "感冒"),Query.EQ("Author", "yanc")) 等等
        /// <returns></returns>
        public static long Count(string connectionString, string databaseName, string collectionName, IMongoQuery query)
        {
            GetServer(connectionString);
            GetDatabase(databaseName);
            long result = 0;
            using (_server.RequestStart(_database))//开始连接数据库。
            {
                MongoCollection<BsonDocument> myCollection = _database.GetCollection<BsonDocument>(collectionName);
                if (null == query)
                {
                    result = myCollection.Count();
                }
                else
                {
                    result = myCollection.Count(query);
                }
            }
            return result;
        }

        #endregion

        #region 索引

        /// <summary>
        /// 创建索引 创建索引 2012-12-12 马山林 添加 
        /// </summary>
        /// <param name="collectionName">集合名</param>
        /// <param name="keyNames"></param>
        public static void CreateIndex(string collectionName, params string[] keyNames)
        {
            MongoHelper.CreateIndex(MongoHelper.connectionString_Default, MongoHelper.database_Default, collectionName, keyNames);
        }

        /// <summary>
        /// 创建索引
        /// </summary>
        /// <param name="connectionString">链接</param>
        /// <param name="databaseName">库名</param>
        /// <param name="collectionName">集合名</param>
        /// <param name="keyNames"></param>
        public static void CreateIndex(string connectionString, string databaseName, string collectionName, params string[] keyNames)
        {
            //db.CacheData_0.ensureIndex({ "URL" : 1, "readall" : 1 },{ "name" : "url" });
            //SafeModeResult result = new SafeModeResult();
            if (null == keyNames)
            {
                return;
            }
            GetServer(connectionString);
            GetDatabase(databaseName);
            using (_server.RequestStart(_database))//开始连接数据库。
            {
                MongoCollection<BsonDocument> myCollection = _database.GetCollection<BsonDocument>(collectionName);
                if (!myCollection.IndexExists(keyNames))
                {
                    myCollection.EnsureIndex(keyNames);
                }
            }
        }

        /// <summary>
        /// 创建索引 2013-01-12 马山林 添加 
        /// </summary>
        /// <param name="collectionName">集合名</param>
        /// <param name="ascKeys">要升序的字段</param>
        /// <param name="descKeys">要降序的字段</param>
        /// <param name="indexName">组合索引名</param>
        public static void CreateIndex(string collectionName, string[] ascKeys, string[] descKeys, string indexName)
        {
            CreateIndex(MongoHelper.connectionString_Default, MongoHelper.database_Default, collectionName, ascKeys, descKeys, indexName);
        }

        /// <summary>
        /// 创建索引 2013-01-12 马山林 添加 
        /// ？现在不能判断索引是否存在
        /// </summary>
        /// <param name="connectionString">链接</param>
        /// <param name="databaseName">库名</param>
        /// <param name="collectionName">集合名</param>
        /// <param name="ascKeys">要升序的字段</param>
        /// <param name="descKeys">要降序的字段</param>
        /// <param name="indexName">组合索引名</param>
        public static void CreateIndex(string connectionString, string databaseName, string collectionName, string[] ascKeys, string[] descKeys, string indexName)
        {
            //db.CacheData_0.ensureIndex({ "URL" : 1, "readall" : 1 },{ "name" : "url" });
            //SafeModeResult result = new SafeModeResult();
            if (indexName == "" && (ascKeys == null || descKeys == null))
            {
                return;
            }
            GetServer(connectionString);
            GetDatabase(databaseName);
            using (_server.RequestStart(_database))//开始连接数据库。
            {
                MongoCollection<BsonDocument> myCollection = _database.GetCollection<BsonDocument>(collectionName);
                IMongoIndexOptions indexOption = null;
                indexOption = IndexOptions.SetName(indexName);
                IMongoIndexKeys indexKey = null;
                if (ascKeys == null)
                {
                    indexKey = IndexKeys.Descending(descKeys);
                }
                else if (descKeys == null)
                {
                    indexKey = IndexKeys.Ascending(ascKeys);
                }
                else
                {
                    indexKey = IndexKeys.Ascending(ascKeys).Descending(descKeys);
                }

                if (!myCollection.IndexExists(indexKey))
                {
                    myCollection.CreateIndex(indexKey, indexOption);
                }
            }
        }

        /// <summary>
        /// 删除索引 2013-01-12 马山林 添加 
        /// </summary>
        /// <param name="connectionString">链接</param>
        /// <param name="databaseName">库名</param>
        /// <param name="collectionName">集合名</param>
        /// <param name="indexName">索引名</param>
        public static void DropIndex(string collectionName, string indexName)
        {
            MongoHelper.DropIndex(MongoHelper.connectionString_Default, MongoHelper.database_Default, collectionName, indexName);
        }

        /// <summary>
        /// 删除索引 2013-01-12 马山林 添加 
        /// </summary>
        /// <param name="connectionString">链接</param>
        /// <param name="databaseName">库名</param>
        /// <param name="collectionName">集合名</param>
        /// <param name="indexName">索引名</param>
        public static void DropIndex(string connectionString, string databaseName, string collectionName, string indexName)
        {
            //SafeModeResult result = new SafeModeResult();
            if (indexName == "" || indexName == null)
            {
                return;
            }
            GetServer(connectionString);
            GetDatabase(databaseName);
            using (_server.RequestStart(_database))//开始连接数据库。
            {
                MongoCollection<BsonDocument> myCollection = _database.GetCollection<BsonDocument>(collectionName);
                //if (!myCollection.IndexExists(indexName))
                //{
                myCollection.DropIndexByName(indexName);
                //}
            }
        }
        #endregion

        #region 获取所有数据库
        /// <summary>
        /// 获取所有数据库 2012-11-29 马山林 添加
        /// </summary>
        /// <param name="connectionString"></param>
        /// <returns></returns>
        public static List<string> GetDBNames(string connectionString)
        {
            List<string> listDBs = new List<string>();
            ////SafeModeResult result = new SafeModeResult();
            GetServer(connectionString);
            IEnumerable<string> dbs = _server.GetDatabaseNames();
            System.Collections.IEnumerator em = dbs.GetEnumerator();
            while (em.MoveNext())
            {
                listDBs.Add(em.Current.ToString());
            }
            return listDBs;
        }

        public static List<string> GetDBNames()
        {
            //SafeModeResult result = new SafeModeResult();
            GetServer(MongoHelper.connectionString_Default);
            IEnumerable<string> dbs = _server.GetDatabaseNames();
            return (List<string>)dbs;
        }

        #endregion

        #region 获取所有表名
        /// <summary>
        /// 获取所有表名  2013-03-25 马山林 添加
        /// </summary>
        /// <param name="connectionString"></param>
        /// <param name="dbName"></param>
        /// <returns></returns>
        public static List<string> GetdsNames(string connectionString, string databaseName)
        {
            List<string> lDts = new List<string>();
            GetServer(connectionString);
            GetDatabase(databaseName);
            using (_server.RequestStart(_database))//开始连接数据库。
            {
                IEnumerable<string> dbs = _database.GetCollectionNames();
                System.Collections.IEnumerator em = dbs.GetEnumerator();
                while (em.MoveNext())
                {
                    lDts.Add(em.Current.ToString());
                }
            }
            return lDts;
        }

        public static List<string> GetdsNames()
        {
            List<string> lDts = new List<string>();
            GetServer(MongoHelper.connectionString_Default);
            GetDatabase(MongoHelper.database_Default);
            using (_server.RequestStart(_database))//开始连接数据库。
            {
                IEnumerable<string> dbs = _database.GetCollectionNames();
                System.Collections.IEnumerator em = dbs.GetEnumerator();
                while (em.MoveNext())
                {
                    lDts.Add(em.Current.ToString());
                }
            }
            return lDts;
        }
        #endregion

        #region 获取表状态
        /// <summary>
        /// 获取表状态 2013-03-25 马山林 添加
        /// </summary>
        /// <param name="connectionString"></param>
        /// <param name="databaseName"></param>
        /// <param name="collectionName"></param>
        /// <returns></returns>
        public static CollectionStatsResult GetDataTableStats(string connectionString, string databaseName, string collectionName)
        {
            GetServer(connectionString);
            GetDatabase(databaseName);
            MongoCollection collection = _database.GetCollection(collectionName);
            using (_server.RequestStart(_database))//开始连接数据库。
            {
                return collection.GetStats();
            }
        }
        /// <summary>
        /// 获取表状态
        /// </summary>
        /// <param name="connectionString"></param>
        /// <returns></returns>
        public static CollectionStatsResult GetDataTableStats(string collectionName)
        {
            GetServer(MongoHelper.connectionString_Default);
            GetDatabase(MongoHelper.database_Default);
            MongoCollection collection = _database.GetCollection(collectionName);
            using (_server.RequestStart(_database))//开始连接数据库。
            {
                return collection.GetStats();
            }
        }

        #endregion

        #region 获取数据库状态

        /// <summary>
        /// 获取数据库状态 2013-03-25 马山林 添加
        /// </summary>
        /// <param name="connectionString"></param>
        /// <param name="databaseName"></param>
        /// <returns></returns>
        public static Hashtable GetDataBaseStats(string connectionString, string databaseName)
        {
            Hashtable ht = new Hashtable();
            CollectionStatsResult[] statsResult = null;
            GetServer(connectionString);
            GetDatabase(databaseName);
            MongoCollection collection = null;// _database.GetCollection(collectionName);
            using (_server.RequestStart(_database))//开始连接数据库。
            {
                IEnumerable<string> dts = _database.GetCollectionNames();
                System.Collections.IEnumerator em = dts.GetEnumerator();
                int i = 0;
                if (em != null)
                {
                    statsResult = new CollectionStatsResult[1];
                    while (em.MoveNext())
                    {
                        collection = _database.GetCollection(em.Current.ToString());
                        if (collection != null)
                        {
                            ht.Add(collection, collection.GetStats());
                        }
                        i++;
                    }
                }
            }
            return ht;
        }

        /// <summary>
        /// 获取数据库状态
        /// </summary>
        /// <param name="connectionString"></param>
        /// <param name="databaseName"></param>
        /// <returns></returns>
        public static Hashtable GetDataBaseStats()
        {
            Hashtable ht = new Hashtable();
            GetServer(MongoHelper.connectionString_Default);
            GetDatabase(MongoHelper.database_Default);
            MongoCollection collection = null;
            using (_server.RequestStart(_database))//开始连接数据库。
            {
                IEnumerable<string> dts = _database.GetCollectionNames();
                System.Collections.IEnumerator em = dts.GetEnumerator();
                int i = 0;
                if (em != null)
                {
                    while (em.MoveNext())
                    {
                        collection = _database.GetCollection(em.Current.ToString());
                        if (collection != null)
                        {
                            ht.Add(collection, collection.GetStats());
                        }
                        i++;
                    }
                }
            }
            return ht;
        }
        #endregion

        #region 创建链接
        /// <summary>
        /// 创建链接
        /// </summary>
        /// <param name="connectionString">服务器链接，可以不加Server=</param>
        /// <returns></returns>
        private static MongoServer CreateServer(string connectionString)
        {
            MongoServer _server = null;
            if (!connectionString.StartsWith("Server="))
            {
                connectionString = "Server=" + connectionString;
            }
            try
            {
                _server = MongoServer.Create(connectionString);
            }
            catch (Exception)
            {

            }
            return _server;
        }
        #endregion
    }

    #region 分页实体

    /// <summary>
    /// 分页实体类
    /// </summary>
    public class PagerInfo
    {
        int _page = 1;//当前页
        int _pageSize = 10;//页大小
        public int Page
        {
            get { return _page; }
            set { _page = value; }
        }
        public int PageSize
        {
            get { return _pageSize; }
            set { _pageSize = value; }
        }
    }
    #endregion
}

